(function(moduleName){
  // 问卷
  sugarcane.module[moduleName] = function(data, answerCallback){
    var thisObj = $(`<div class="app-questionaires">
      <div class="questionaires-contain">
        <div class="questionaires-title"></div>
        <div class="questionaires-date"></div>
        <div class="questionaires-content"></div>
        <div class="questionaires-list"></div>
        <div class="questionaires-btn">
          <div class="btn j-btn fn-hide"></div>
          <div class="btn j-btnfun btn-submit j-submit fn-hide">提交</div>
          <div class="btn j-btnfun btn-reanswer j-reanswer fn-hide">重答</div>
        </div>
        <div class="questionaires-count"></div>
      </div>
    </div>`);

    // data
    thisObj.find('.questionaires-title').html(data['title']);
    thisObj.find('.questionaires-date').html('活动时间：'+data['startTime']+' — '+data['endTime']);
    thisObj.find('.questionaires-content').html(data['description']);

    var isInteractive = data['isInteractive'], // 0：未参与；1：已参与
      interactiveStatus = data['interactiveStatus']; // 1=未开始，2=进行中，3已结束

    // if(data['questions'].length){
    //   questionView();
    // }

    // function questionView(){
      $.each(data['questions'], function(index,item){
        if (this['type'] == 3) {
          if (interactiveStatus == 1) {
            var _write = 'readonly';
          } else if (interactiveStatus == 2) {
            if (isInteractive == 1) {
              var _write = 'readonly';
            } else {
              var _write = '';
            }
          } else {
            var _write = 'disabled';
          }
          if(!this['answer']) {
            this['answer'] = '';
          }
          var _ddHtml = '<dd><textarea class="j-answer" data-type="'+ this['type'] +'" data-questionid="'+this['id']+'" '+_write+'>'+ this['answer'] +' </textarea></dd>';
          
          // var _ddHtml = '<dd><input class="j-answer" data-type="'+ this['type'] +'" data-questionid="'+this['id']+'" type="text" '+_write+' value="'+ this['answer']+'"></dd>';
        } else {
          var _ddHtml = '',_type = this['type'];
          $.each(this['options'], function(){
            if (this['isCheck'] == 1) {
              var _checked = 'checked';
            } else {
              var _checked = '';
            }
            if (interactiveStatus == 3) {
              _checked += ' discheck';
            }
            _ddHtml += `
              <dd class="check-dd">
                <div class="item-checkbox">
                  <div data-questionid="`+this['questionId']+`" data-type="`+ _type +`" data-id="`+this['id']+`" class="j-option checkbox `+_checked+`"><span></span></div>
                </div>
                <div class="item-content">`+this['option']+`</div>
              </dd>
            `;
          });
        }
        var _optionObj = $('<dl><dt>'+(1+ index)+'.' +this['question']+'</dt>'+_ddHtml+'</dl>');
        if(!sugarcane['app']['userId']){
          _optionObj.find('.j-answer').attr('disabled','disabled');
        }
        // 进行中的活动
        if (interactiveStatus == 2) {
          if (sugarcane['app']['isShare']) {
            // 去下载
            _optionObj.find('dd').on(tap, function(){
              sugarcane['openApp']({'id':data['id'],'docType': data['docType']});
            });
          } else {
            // 交互
            if (isInteractive == 0) {
              var _type = this['type'];
              _optionObj.find('dd').on(tap, function(){
                if (sugarcane['app']['userId']) {
                  if (_type == 1) {
                    _optionObj.find('dd .checkbox').removeClass('checked');
                    $(this).find('.checkbox').addClass('checked');
                  } else if (_type == 2) {
                    if ($(this).find('.checkbox').hasClass('checked')) {
                      $(this).find('.checkbox').removeClass('checked');
                    } else {
                      $(this).find('.checkbox').addClass('checked');
                    }
                  }
                } else {
                  peach.login({
                    'success': function(userInfo){
                      sugarcane['app']['userId'] = userInfo['userId'];
                      answerCallback();
                    }
                  });
                }
              });            
            }
          }
        }

        thisObj.find('.questionaires-list').append(_optionObj);
      });

      if (interactiveStatus == 1) {
        thisObj.find('.questionaires-btn .btn').addClass('fn-hide');
        thisObj.find('.questionaires-btn .j-btn').removeClass('fn-hide').addClass('disabled').html('活动未开始');
      } else if (interactiveStatus == 2) {
        if (isInteractive == 0) {
          thisObj.find('.questionaires-btn .btn').addClass('fn-hide');
          thisObj.find('.questionaires-btn .j-btnfun').removeClass('fn-hide');

          if (sugarcane['app']['isShare']) {
            thisObj.find('.questionaires-btn .j-btnfun').on(tap, function(){
              // 去下载
              sugarcane['openApp']({'id': data['id'],'docType': data['docType']});
            });
          } else {
            // 绑定提交
            thisObj.find('.questionaires-btn .j-submit').on(tap, function(){
              if (sugarcane['app']['userId']) {
                // 已登录，直接提交
                var postQuestion = {
                  "id": data['id'],
                  "answers": []
                };


                var finishState = true;
                var optionData = {};
                //判断每一个问题的选择填写状态
                thisObj.find('.questionaires-list dl').each(function(){
               
                  var _this = this;
                  if ($(_this).find('.j-answer').length) {//问答类
                    if (!$.trim($(_this).find('.j-answer').val())) {
                      finishState = false;
                    }
                  } else {//选择类
                    var _optionState = false;
                    $(_this).each(function(){
                      if ($(_this).find('.j-option').hasClass('checked')) {
                        _optionState = true;
                      }
                    });
                    if (!_optionState) {
                      finishState = false;
                    }
                  }
                });

                if (!finishState) {
                  // 未完成
                  peach.toast('请填写完问卷！')
                  return false;
                } else {
                  thisObj.find('.questionaires-list dl').each(function(){
                    var _this = this;
                    if ($(_this).find('.j-answer').length) {//问答类
                      postQuestion['answers'].push({
                        "questionId": $(_this).find('.j-answer').data('questionid'),
                        "option": $.trim($(_this).find('.j-answer').val()),
                        "type":  $(_this).find('.j-answer').data('type')
                      });
                    }else{
                      $(_this).each(function(){
                        var _optionobj = {
                          'questionId':  $(_this).find('.j-option.checked').data('questionid'),
                          'optionId': [],
                          "type":  $(_this).find('.j-option.checked').data('type')
                        }
                        $(_this).find('.j-option').forEach(function (item) {
                          if ($(item).hasClass('checked')) {
                            _optionobj.optionId.push($(item).data('id'));
                          }
                        });
                          
                        postQuestion['answers'].push(_optionobj);

                      });
                    }
                  });
                }


                if(finishState){//完成问卷填写
                  // ajax
                  sugarcane.ajaxApi({
                    "url": "/interactive/question",
                    "data": postQuestion,
                    "callback": function(res){
                      if (res['code'] == 0) {
                        peach.toast('提交成功')
                        answerCallback();
                      } else {
                        peach.alert(res['message']);
                      }
                    }
                  });
                }else{
                  peach.toast('请填写完问卷！')
                }
                
              } else {
                // 去登录
                peach.login({
                  'success': function(userInfo){
                    if(userInfo['userId']) {
                      sugarcane['app']['userId'] = userInfo['userId'];
                      answerCallback();
                    }
                  }
                });
              }
            });
            //绑定重答
            thisObj.find('.questionaires-btn .j-reanswer').on(tap,function(){
              var ischecked = false , hasval = false;
              thisObj.find('.questionaires-list .j-option').each(function(){
                if($(this).hasClass('checked')){
                  ischecked = true;
                  return false; 
                }
              });
              thisObj.find('.questionaires-list .j-answer').each(function(){
                if($(this).val()){
                  hasval = true;
                  return false; 
                }
              });
              if(ischecked || hasval){
                //问卷确认重答
                peach.confirm ({
                  'title': '重答确认',
                  'message': '确认清空当前问卷回答？',
                  'btnSure': '确认',
                  'btnCancel':'取消',
                  'sureValue': 'sure',
                  'cancelValue': 'cancel',
                  'sureFunc': function(jsonData){
                    if(jsonData['status'] == 'sure'){
                      thisObj.find('.questionaires-list .j-option').each(function(){
                        $(this).removeClass('checked'); 
                      });
                      thisObj.find('.questionaires-list .j-answer').each(function(){
                        $(this).val('');
                      });
                    }

                  }
                }); 
              }else{
                peach.toast('请先答题！')
              }
              
            });
          }
        } else {
          thisObj.find('.questionaires-btn .btn').addClass('fn-hide');
          thisObj.find('.questionaires-btn .j-btn').removeClass('fn-hide').addClass('disabled').html('已参与');
        }
      } else {
        thisObj.find('.questionaires-btn .btn').addClass('fn-hide');
        thisObj.find('.questionaires-btn .j-btn').removeClass('fn-hide').addClass('disabled').html('活动已结束');
      }

      thisObj.find('.questionaires-count').html('已有 '+data['participateNumber']+' 人参与');

      return thisObj;
    // }
   
  };
  sugarcane.module['state'][moduleName] = 'load';
  sugarcane.module.callback(moduleName);
}("question"));